#include "HomeDirectoryWidget.h"
#include "HomeDirectoryTree.h"
#include "HomeDirectoryFileEdit.h"

#include <QtWidgets>

HomeDirectoryWidget::HomeDirectoryWidget(shell::PanelAdaptor_interface *adaptor, shell::Access_interface &shell_access)
    : _adaptor(adaptor)
    , _shell_access(shell_access)
{
    _file_name_editor = new FileEdit;
    _tree             = new HomeDirectoryTree(shell_access.filesystem_model(), {".git"});

    QVBoxLayout * layout  = new QVBoxLayout(this);
    
    _toolbar = new QToolBar;

    /// \todo Панель инструментов выглядит небрежно для тёмной темы из-за иконок от светлой темы.
    /// \todo Панель инструментов занимает много места на мониторах с низким разрешением.
    /// Надо придумать, как оптимизировать место.
    _toolbar->setVisible(false);

    layout->addWidget(_toolbar);
    layout->addWidget(_file_name_editor);
    layout->addWidget(_tree);

    _file_name_editor->setVisible(false);
    
    layout->setMargin(0);
    layout->setSpacing(0);

    createActions();
    fillToolbar();
    resetWorkDirectory();

    /// \todo Поиск работает плохо, пока выключаем
    // connect(_file_name_editor, &QLineEdit::textChanged, 
    //         this, [this](const QString & seach_name) {
    //             _tree->setSearchNameToSortProxy(seach_name);
    //         });

    connect(fileNameEditor(), &QLineEdit::returnPressed, this, 
    [this]{
        fileNameEditor()->setVisible(false);
        switch(_choice)
        {
        case FileEditChoice::NewFile:
        {
            QString path = _tree->addFileToDirectory(fileNameEditor()->text());
            if (!path.isEmpty())
                _shell_access.openFile(path);
            break;
        }
        case FileEditChoice::NewDirectory:
            _tree->addDirectoryToDirectory(fileNameEditor()->text());
            break;
        case FileEditChoice::Find:
            break;
        case FileEditChoice::NewFileHome:
        {
            QString path = _tree->addFileToHomeDirectory(fileNameEditor()->text());
            if (!path.isEmpty())
                _shell_access.openFile(path);
            break;
        }
        case FileEditChoice::NewDirectoryHome:
            _tree->addDirectoryToHomeDirectory(fileNameEditor()->text());
            break;
        }
    });

    connect(_tree, &QTreeView::activated, this, 
            [this]()
            {
                QString   path = _tree->selectedPath();
                QFileInfo fi(path);

                if (fi.isFile())
                    _shell_access.openFile(path);
            });
}

HomeDirectoryWidget::~HomeDirectoryWidget()
{
}

bool HomeDirectoryWidget::setSelectorPosition(const QString & path)
{
    return _tree->setSelectorPosition(path);
}

void HomeDirectoryWidget::resetWorkDirectory() {
    _shell_access.filesystem_model().setRootPath(QDir::currentPath());
    _tree->resetWorkDirectory();
}

void HomeDirectoryWidget::fillToolbar()
{
    _toolbar->addAction(_act_new_file);
    _toolbar->addAction(_act_new_directory);
    _toolbar->addAction(_act_root_new_file);
    _toolbar->addAction(_act_root_new_directory);
    /// \todo Поиск работает плохо, пока выключаем
    // _toolbar->addAction(_act_find_item);
}

void HomeDirectoryWidget::createActions()
{
    const QIcon open_icon = QIcon::fromTheme("document-open", QIcon(":/images/document-open"));
    _act_open_file = new QAction(open_icon, tr("Open"), this);
    /// \todo Не работает. Позже можно удалить
    // _act_open_file->setShortcuts(QKeySequence::Open);
    _act_open_file->setStatusTip(tr("Open selected file"));
    connect(_act_open_file, &QAction::triggered, this,
            [this](){
                if (_tree->isFileSelected())
                    _shell_access.openFile(_tree->selectedPath());

            });
    addAction(_act_open_file);

    _act_open_file_in_associated_program = new QAction(tr("Open in associated program"), this);
    _act_open_file_in_associated_program->setStatusTip(tr("Open selected file in associated program"));
    connect(_act_open_file_in_associated_program, &QAction::triggered, this,
            [this](){
                if (_tree->isFileSelected())
                    QDesktopServices::openUrl(QUrl("file:///"+_tree->selectedPath(), QUrl::TolerantMode));
    });
    addAction(_act_open_file);

    const QIcon document_new_icon = QIcon::fromTheme("document-new", QIcon(":/images/document-new"));
    _act_new_file = new QAction(document_new_icon, tr("Create file in selected directory"), this);
    connect(_act_new_file, &QAction::triggered, this, 
            [this]{
                _choice = FileEditChoice::NewFile;
                fileNameEditor()->setVisible(true);
                fileNameEditor()->setPlaceholderText("Enter file name...");
                fileNameEditor()->setFocus();
            });
    addAction(_act_new_file);

    const QIcon folder_new_icon = QIcon::fromTheme("folder-new", QIcon(":/images/folder-new"));
    _act_new_directory = new QAction(folder_new_icon, tr("Create directory in selected directory"), this);
    connect(_act_new_directory, &QAction::triggered, this, 
            [this]{
                _choice = FileEditChoice::NewDirectory;
                fileNameEditor()->setVisible(true);
                fileNameEditor()->setPlaceholderText("Enter directory name...");
                fileNameEditor()->setFocus();
            });
    addAction(_act_new_directory);

    /// \todo Поиск работает плохо, пока выключаем
    // const QIcon find_item_icon = QIcon::fromTheme("edit-find", QIcon(":/images/edit-find"));
    // _act_find_item = new QAction(find_item_icon, tr("Find file or directory in selected directory"), this);
    // connect(_act_find_item, &QAction::triggered, this, 
    //         [this]{
    //             _choice = FileEditChoice::Find;
    //             fileNameEditor()->setVisible(true);
    //             fileNameEditor()->setPlaceholderText("Find files or direcrories...");
    //             fileNameEditor()->setFocus();
    //         });
    // addAction(_act_find_item);

    const QIcon delete_item_icon = QIcon::fromTheme("edit-delete", QIcon(":/images/edit-delete"));
    _act_delete_file = new QAction(delete_item_icon, tr("Delete"), this);
    _act_delete_file->setShortcut(QKeySequence::Delete);
    connect(_act_delete_file, &QAction::triggered, _tree, &HomeDirectoryTree::onDelete);
    addAction(_act_delete_file);

    const QIcon copy_icon = QIcon::fromTheme("edit-copy", QIcon(":/images/edit-copy"));
    _act_duplicate_file = new QAction(copy_icon, tr("Duplicate file"), this);
    /// \todo Не работает. Позже можно удалить
    // _act_duplicate_file->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_F2));
    connect(_act_duplicate_file, &QAction::triggered, _tree, &HomeDirectoryTree::onDuplicateFile);
    addAction(_act_duplicate_file);

    _act_rename_file = new QAction(tr("Rename"), this);
    _act_rename_file->setShortcut(QKeySequence(Qt::Key_F2));
    connect(_act_rename_file, &QAction::triggered, this,
            [this](){
                if (_tree->isFileSelected())
                    _tree->editCurrent();
            });
    addAction(_act_rename_file);

    _act_collapse_all = new QAction(tr("Collapce all"), this);
    connect(_act_collapse_all, &QAction::triggered, this, 
            [this](){ 
                _tree->collapseAll();
            });
    addAction(_act_collapse_all);

    _act_expand_all = new QAction(tr("Expand all"), this);
    connect(_act_expand_all, &QAction::triggered, this, 
            [this](){ 
                _tree->expandAll(); 
            });
    addAction(_act_expand_all);

    // const QIcon refresh_icon = QIcon::fromTheme("view-refresh", QIcon(":/images/view-refresh"));
    // _act_refresh = new QAction(refresh_icon, tr("Refresh directory"), this);
    // connect(_act_refresh, &QAction::triggered, this, 
    //         [this](){
    //             _tree->resetWorkDirectory();
    //         });
    // addAction(_act_refresh);

    // const QIcon root_doc_new_icon = QIcon::fromTheme(":/images/document-new-home", QIcon(":/images/document-new-home"));
    _act_root_new_file = new QAction(/*root_doc_new_icon,*/ tr("Create file in HOME directory"), this);
    connect(_act_root_new_file, &QAction::triggered, this, 
            [this](){ 
                _choice = FileEditChoice::NewFileHome;
                fileNameEditor()->setVisible(true);
                fileNameEditor()->setPlaceholderText("Enter file name...");
                fileNameEditor()->setFocus();
            });
    addAction(_act_root_new_file);

    // const QIcon root_folder_new_icon = QIcon::fromTheme(":images/folder-new-home.png", QIcon(":images/folder-new-home.png"));
    _act_root_new_directory = new QAction(/*root_folder_new_icon,*/ tr("Create directory in HOME directory"), this);
    connect(_act_root_new_directory, &QAction::triggered, this, 
            [this](){
                _choice = FileEditChoice::NewDirectoryHome;
                fileNameEditor()->setVisible(true);
                fileNameEditor()->setPlaceholderText("Enter directory name...");
                fileNameEditor()->setFocus();
            });
    addAction(_act_root_new_directory);
}

void HomeDirectoryWidget::contextMenuEvent(QContextMenuEvent *event)
{
    QMenu menu(this);

    if (_tree->isFileSelected()) {
        QFileInfo fi (_tree->selectedPath());

        if (fi.isDir()) {
            menu.addAction(_act_new_file);
            menu.addAction(_act_new_directory);
            menu.addSeparator();
        }
        else {
            menu.addAction(_act_open_file);
            menu.addAction(_act_open_file_in_associated_program);
            menu.addSeparator();
            menu.addAction(_act_duplicate_file);
        }

        menu.addAction(_act_rename_file);
        menu.addAction(_act_delete_file);
        menu.addSeparator();
    }

    menu.addAction(_act_collapse_all);
    menu.addAction(_act_expand_all);
    // menu.addAction(_act_refresh);

    menu.addSeparator();
    menu.addAction(_act_root_new_file);
    menu.addAction(_act_root_new_directory);

    menu.exec(event->globalPos());
}


